<?php

namespace app\common\utils;

use think\cache\Driver;
use think\cache\driver\Redis;
use think\facade\Cache;

/**
 * Redis方法封装
 */
class RedisUtils extends Redis
{
    /**
     * @return Driver
     */
    public static function init(): Driver
    {
        return Cache::store('redis');
    }

    /**
     * 使用redis加锁
     * @param string $key
     * @param int $expire
     * @return bool
     * @throws \RedisException
     */
    public function lock(string $key, int $expire = 60): bool
    {
        $lockResult = $this->handler->setnx($key, 1);
        if (!$lockResult) {
            return false;
        } else {
            $this->handler->expire($key, $expire);
            return true;
        }
    }

    /**
     * 使用redis解锁
     * @param string $key
     * @return bool
     * @throws \RedisException
     */
    public function unlock(string $key): bool
    {
        $this->handler->del($key);
        return true;
    }

}